/**
 * 
 */
package com.anyuan.wx.util;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.anyuan.wx.menu.Menu;


/**
 * @author liuyanbin
 * @date 2014-2-17
 */
public class MenuUtil {
	
	private static Logger log = LoggerFactory.getLogger(Menu.class);
	
	public final static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

	public final static String menu_get_url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";

	public final static String menu_delete_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

	//创建菜单
		public static boolean createMenu(String accessToken,Menu menu){
			boolean result = false;
			String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
			//把菜单对象封装成json格式
			String jsonMenu = JSONObject.fromObject(menu).toString();
			
			JSONObject jsonObject =  CommonUtil.httpRequest(url, "POST", jsonMenu);
			
			if(null!=jsonObject)
			{
				int errorcode = jsonObject.getInt("errcode");
				if(0== errorcode)
					result = true;
				else
				{
					result = false;
					log.error("创建菜单失败,errcode{},errmsg{}",jsonObject.getInt("errcode"),jsonObject.getString("errmsg"));
				}
			}
			return result;
			
		}
		
		//删除菜单
		public static int deleteMenu(String accessToken,Menu menu){
			int result = 0;
			String url = menu_delete_url.replace("ACCESS_TOKEN", accessToken);
			//把菜单对象封装成json格式
			String jsonMenu = JSONObject.fromObject(menu).toString();
			
			JSONObject jsonObject =  CommonUtil.httpRequest(url, "GET", jsonMenu);
			
			if(null!=jsonObject)
			{
				if(0!= jsonObject.getInt("errcode"))
				{
					result = jsonObject.getInt("errcode");
					log.error("创建菜单失败,errcode{},errmsg{}",jsonObject.getInt("errcode"),jsonObject.getString("errmsg"));
				}
			}
			return result;
			
		}
		
		//获取菜单
		public static String getMenu(String accessToken,Menu menu){
			String result = null;
			String url = menu_get_url.replace("ACCESS_TOKEN", accessToken);
			
			JSONObject jsonObject =  CommonUtil.httpRequest(url, "GET", null);
			
			if(null!=jsonObject)
			{
				if(0!= jsonObject.getInt("errcode"))
				{
					result = jsonObject.toString();
					
				}
			}
			return result;
			
		}
		

}
